﻿using Com.Lancetinc.Evs.Resources;
using Microsoft.Xaml.Behaviors;
using System.Windows;
using System.Windows.Controls;

namespace Com.Lancetinc.Evs.Helpers
{
    public class DynamicSourceImageBehavior : Behavior<Image>
    {
        #region SourceName

        public static readonly DependencyProperty SourceNameProperty =
            DependencyProperty.Register(nameof(SourceName),
                typeof(string),
                typeof(DynamicSourceImageBehavior), new PropertyMetadata(null, (d, e) =>
                {
                    if (d is not DynamicSourceImageBehavior self) return;

                    self.OnSourceChanged();
                }));

        public string SourceName
        {
            get => (string)GetValue(SourceNameProperty);
            set => SetValue(SourceNameProperty, value);
        }
        #endregion

        private void OnSourceChanged()
        {
            if (AssociatedObject == null)
                return;

            if (string.IsNullOrEmpty(SourceName))
            {
                AssociatedObject.Source = null;
                return;
            }

            AssociatedObject.Source = ResourceHelper.GetImage(SourceName);
        }
    }
}